#include "c_types.h"
#include "car.h"
/*放置控制小车，和循迹的控制函数*/
/*电机引脚初始化
IN1	D5          PWM1 ENA	D7 
IN2	D6          PWM2 ENB	D8
IN3	D3         
IN4	D4          
循迹 
INPUT D1
INPUT D2
INPUT A0 要用if判断高低电平是否超过1k

循迹模块 输入电压 3.3v、5v
*/
void carInit(void){
    pinMode(IN1,OUTPUT); //D0 IN1
    pinMode(IN2,OUTPUT); //D8 IN2
    pinMode(IN3,OUTPUT);  //D3 IN3
    pinMode(IN4,OUTPUT); //D4 IN4
    pinMode(PWM1,OUTPUT);//D5 PWM1
    pinMode(PWM2,OUTPUT);//D6 PWM2
    pinMode(XUN1,INPUT_PULLUP); // D1循迹模块 左边
    pinMode(XUN2,INPUT_PULLUP);// D2 循迹模块 右边
    //初始化电机
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
void pwmInit(void){
    /*初始化PWM设置  720ok 620ok 550ok 400ok 200ok 初始速度*/
  analogWriteFreq(10);
  analogWriteRange(1024);
  analogWrite(PWM1, baseSpeed);
  analogWrite(PWM2, baseSpeed);
}
//前进
void forward(){ 
  analogWrite(PWM1, baseSpeed);
  analogWrite(PWM2, baseSpeed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}
//后退
void backward(){
  analogWrite(PWM1, baseSpeed);
  analogWrite(PWM2, baseSpeed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
}
//停车
void stopcar(){
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, LOW);
    digitalWrite(IN3, LOW);
    digitalWrite(IN4, LOW);
 //   analogWrite(PWM1, 0);
 //   analogWrite(PWM2, 0);
}
//专线采用差速转向
void leftcar(){
 /*   analogWrite(PWM1, 600);//720ok 620ok 550ok 400ok 200ok
    analogWrite(PWM2, 0);//720ok 620ok 550ok 400ok 200ok 
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, HIGH);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, LOW);*/
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, LOW);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, LOW);
}
void rightcar(){
  /*  analogWrite(PWM1, 0);//720ok 620ok 550ok 400ok 200ok
    analogWrite(PWM2, 600);//720ok 620ok 550ok 400ok 200ok 
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, HIGH);
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, LOW);*/
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, HIGH);
    digitalWrite(IN3, LOW);
    digitalWrite(IN4, LOW);
}
//pwm 5档
void pwmCar(uint8 mod){
	// 输出PWM，占空比为 100/255
  analogWrite(PWM1,720);	
  analogWrite(PWM2,720);	
}
/*循迹模块 循迹模块思路改为用扫描模式，io口扫描，定时器中断太慢而且容易卡
循迹多加一种状态，为直走
走线方法摇头走*/
void tracing(){
    uint8 left;
    uint8 right;
    uint8 flag = 0;
    u16 mid;
  
    //1000为高电平
    u8 i = 0;
    mid = analogRead(A0);
    left = digitalRead(XUN1); //检测到黑线为高电平，灭灯
    right = digitalRead(XUN2);
    
    i = left +right;
    if(mid>1000){
        if(i==0){                
        forward();
        }
    }
    if(left==1){
        leftcar();
        left = 0;
    }
    if(right==1){
        rightcar();
        right = 0;
    }
    if(i==2){  
        stopcar();
        i = 0 ;
  }

  //  switch a:
//    case 1 
}

//中间循迹模块的ADC引脚 sensorValue = analogRead(analogInPin);

